﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Carbon.Web.Forms.jQueryForms
{
    public interface ICheckBoxListItemCollection : IListEditorItemCollection
    {

    }

    [Serializable]
    public class CheckBoxListItemCollection<T, TKey> : ListEditorItemCollection<T>, ICheckBoxListItemCollection
    {
		#region Fields (1)
		private Func<T, TKey> m_IdGenerator = default(Func<T, TKey>);
		#endregion

		#region Properties (2)
		public Func<T, TKey> IdGenerator
        {
            get
            {
                 if (m_IdGenerator == null)  throw new NullReferenceException("m_IdGenerator");
                return m_IdGenerator;
            }
        }
		public IEnumerable<TKey> SelectedIds
        {
            get
            {
                return this.Where(i => i.Selected).Select(i => IdGenerator(i.Model)).ToArray();
            }
            set
            {
                foreach (ListEditorItem<T> item in this)
                {
                    item.Selected = false;
                }

                Dictionary<TKey, ListEditorItem<T>> itemsById = this.ToDictionary(i => IdGenerator(i.Model));

                foreach (TKey entityKey in value)
                {
                     if ((itemsById.ContainsKey(entityKey) == false))  throw new InvalidOperationException("(itemsById.ContainsKey(entityKey) == false)");

                    itemsById[entityKey].Selected = true;
                }
            }
        }
		#endregion

		#region Constructors (5)
		public CheckBoxListItemCollection(Func<T, string> nameGenerator)
            : base(nameGenerator)
            {
            }

		public CheckBoxListItemCollection(IEnumerable<ListEditorItem<T>> collection, Func<T, string> nameGenerator)
          : base(collection, nameGenerator)
          {
          }

		public CheckBoxListItemCollection(int capacity, Func<T, string> nameGenerator)
            : base(capacity, nameGenerator)
            {
            }

		public CheckBoxListItemCollection(IEnumerable<T> objects, Func<T, string> nameGenerator, bool defaultSelected)
            : base(objects, nameGenerator, defaultSelected)
            {
            }

		public CheckBoxListItemCollection(IEnumerable<T> objects, Func<T, TKey> idGenerator, Func<T, String> nameGenerator, bool defaultSelected)
            : base(objects, nameGenerator, defaultSelected)
        {
            this.m_IdGenerator = idGenerator;
                
        }
		#endregion
    }
}
